<template>
    <div class="MaterialManage">
        <div class="condition">
            <div class="condition_1 flex">
                <div class="name">
                    <div>物资名称:</div>
                    <el-input placeholder="请输入物资名称" v-model="List.Name" :disabled="filterShow" />
                    <div @click="searchChange('展开')" class="filter">
                        展开高级筛选 <i :class="filterShow === true ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
                    </div>
                </div>
                <div class="btn flex">
                    <div @click="searchChange('重置')">重置</div>
                    <div @click="searchChange('查询')">查询</div>
                </div>
            </div>
            <div class="condition_2" v-show="filterShow === true">
                <div class="List flex">
                    <div>所属厂区</div>
                    <el-select v-model="List.FactoryArea" placeholder="请选择所属厂区">
                        <el-option v-for="item in factoryList" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </div>
                <div class="List flex">
                    <div>物资类型</div>
                    <el-select v-model="List.Type" placeholder="请选择物资类型">
                        <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </div>
                <div class="List flex">
                    <div>物资编号</div>
                    <el-input placeholder="请输入物资编号" v-model="List.no" />
                </div>
                <div class="List flex">
                    <div>物资名称</div>
                    <el-input placeholder="请输入物资名称" v-model="List.Name" />
                </div>
                <div class="List flex">
                    <div>规格</div>
                    <el-input placeholder="请输入规格" v-model="List.Specs" />
                </div>
                <div class="List flex">
                    <div>数量</div>
                    <el-input placeholder="请输入数量" v-model="List.Num" />
                </div>
                <div class="List flex">
                    <div>所在位置</div>
                    <el-input placeholder="请输入所在位置" v-model="List.local" />
                </div>
                <div class="List flex">
                    <div>负责人姓名</div>
                    <el-input placeholder="请输入负责人姓名" v-model="List.ManagerName" />
                </div>
                <div class="List flex">
                    <div>负责人电话</div>
                    <el-input placeholder="请输入负责人电话" v-model="List.ManagerPhone" />
                </div>
            </div>
            <div class="condition_3">
                <div v-for="(item, index) in filterList" :key="item">
                    {{ item }}
                    <i class="el-icon-close" @click="searchChange('删除', item)"></i>
                </div>
            </div>
        </div>
        <div class="Line"></div>
        <div class="Btn flex">
            <div></div>
            <div class="BtnList flex">
                <div @click="operate('新增')">
                    <i class="el-icon-plus"></i>新增
                </div>
                <div @click="operate('删除')">
                    <i class="el-icon-minus"></i>删除
                </div>
            </div>
        </div>
        <div class="table">
            <el-table :data="tableData" style="width: 100%" :height="filterShow === true ? '700px' : '815px'"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="序号" width="60" align="center">
                    <template #default="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column v-for="item in tableList" :key="item.prop" :prop="item.prop" :label="item.label"
                    :width="item.width" align="center" />
                <el-table-column label="操作" width="60" align="center">
                    <template slot-scope="scope">
                        <el-button @click="handleClick(scope.row)" type="text" size="small">编辑</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <Dialog ref="dialog" :title="title" @addEventListener="addEventListener" :List="dialogList" />
    </div>
</template>
<script>
import dayjs from "dayjs";
import axios from "axios";
import Dialog from "./MaterialManage/Dialog.vue";
export default {
    name: 'MaterialManage',
    components: {
        Dialog
    },

    data() {
        return {
            url: "http://10.199.98.2:8086/3DInterface_D/Business/EmergManage",
            filterShow: false,
            factoryList: [],
            typeList: [],
            List: {
                FactoryArea: "",
                Type: "",
                no: "",
                Name: "",
                Specs: "",
                Num: "",
                local: "",
                ManagerName: "",
                ManagerPhone: "",
                Unit: "",
                StartDate: "",
                ScrapDate: "",
            },
            filterList: [],
            tableData: [],
            tableList: [
                { prop: '所属厂区', label: '所属厂区', width: '' },
                { prop: '物资类型', label: '物资类型', width: '' },
                { prop: '物资编号', label: '物资编号', width: '' },
                { prop: '物资名称', label: '物资名称', width: '' },
                { prop: '物资规格', label: '规格', width: '' },
                { prop: '物资数量', label: '数量', width: '' },
                { prop: '所在位置', label: '所在位置', width: '' },
                { prop: '物资开始日期', label: '开始日期', width: '' },
                { prop: '物资报废日期', label: '报废日期', width: '' },
                { prop: '负责人姓名', label: '负责人姓名', width: '' },
                { prop: '负责人电话', label: '负责人电话', width: '' },
            ],
            title: "",
            multipleSelection: [],
            dialogList: {},
            keyToChineseMap: {
                FactoryArea: '所属厂区',
                Type: '物资类型',
                no: '物资编号',
                Name: '物资名称',
                Specs: '物资规格',
                Num: '物资数量',
                local: '所在位置',
                ManagerName: '负责人姓名',
                ManagerPhone: '负责人电话',
                Unit: '物资单位',
                StartDate: '物资开始日期',
                ScrapDate: '物资报废日期'
            },
            oldData: {}
        }
    },
    watch: {
        'List.FactoryArea': {
            handler(newVal) {
                this.List.Type = ""
                this.getType(newVal)
            },
            deep: true
        }
    },
    methods: {
        async getList() {
            await axios.get(this.url + `/Platform/yjwz_bb_cqss`).then(res => {
                const options = res.data.data.map(item => ({
                    value: item["所属厂区"],
                    label: item["所属厂区"]
                }));
                this.factoryList = options;
            }).catch(err => {
                console.log(err);
            })
            this.getType("")
        },
        async getType(val) {
            await axios.get(this.url + `/Platform/yjwz_bb_wzss?factoryArea=${val}`).then(res => {
                const options = res.data.data.map(item => ({
                    value: item["物资类型"],
                    label: item["物资类型"]
                }));
                this.typeList = options;
            }).catch(err => {
                console.log(err);
            })
        },
        searchChange(val, del) {
            const requiredFields = ['所属厂区', '物资类型', '物资编号', '物资名称', '规格', '数量', '所在位置', '负责人姓名', '负责人电话'];
            if (val === '重置') {
                this.List = {
                    FactoryArea: "",
                    Type: "",
                    no: "",
                    Name: "",
                    Specs: "",
                    Unit: "",
                    Num: "",
                    local: "",
                    StartDate: "",
                    ScrapDate: "",
                    ManagerName: "",
                    ManagerPhone: ""
                }
                this.getTable(this.List)
                this.filterList = []
            } else if (val === '查询') {
                this.getTable(this.List)
                let filterList = Object.entries(this.List).filter(([key, value]) => value !== "").map(([key, value]) => {
                    const chineseName = this.keyToChineseMap[key] || key;
                    return `${chineseName}:${value}`;
                });

                this.filterList = filterList
            } else if (val === '展开') {
                this.filterShow = !this.filterShow;
            } else if (val === '删除') {
                const chineseToKeyMap = {};
                Object.entries(this.keyToChineseMap).forEach(([key, chinese]) => {
                    chineseToKeyMap[chinese] = key;
                });
                this.filterList = this.filterList.filter(item => item !== del);

                let list = {};

                // 1. 将 filterList 中的中文键名转换为英文键名   
                this.filterList.forEach(item => {
                    const [chineseKey, value] = item.split(':');
                    const englishKey = chineseToKeyMap[chineseKey] || chineseKey; // 如果没有映射，保留原键名
                    list[englishKey] = value.trim();
                });

                // 2. 确保 requiredFields 中的必填字段在 list 中存在（值为空字符串）   
                requiredFields.forEach(field => {
                    const englishKey = chineseToKeyMap[field];
                    if (englishKey && !list.hasOwnProperty(englishKey)) {
                        list[englishKey] = "";
                    }
                });

                // 3. 确保 list 的结构和 List 完全一致（包括非必填字段）   
                Object.keys(this.List).forEach(key => {
                    if (!list.hasOwnProperty(key)) {
                        list[key] = "";
                    }
                });
                this.List = list;
                this.getTable(this.List)
            }
        },
        async getTable(obj) {
            const options = {
                method: 'POST',
                url: 'http://10.199.98.2:8086/3DInterface_D/Business/EmergManage/Platform/yjwz_bb_zsgc',
                data: {
                    TIP: 'select',
                    SQL: `select FactoryArea 所属厂区, Type 物资类型, no 物资编号, Name 物资名称, Specs 物资规格, Unit 物资单位, Num 物资数量, local 所在位置, StartDate 物资开始日期, ScrapDate 物资报废日期, ManagerName 负责人姓名, ManagerPhone 负责人电话 FROM imp_emergmanage.emerg_matlist x where FactoryArea LIKE CONCAT(\'${obj.FactoryArea}%\', \'\', \'%\') and Type LIKE CONCAT(\'${obj.Type}%\', \'\', \'%\') and no LIKE CONCAT(\'${obj.no}%\', \'\', \'%\') and Name LIKE CONCAT(\'${obj.Name}%\', \'\', \'%\') and Specs LIKE CONCAT(\'${obj.Specs}%\', \'\', \'%\') and Unit LIKE CONCAT(\'${obj.Unit}%\', \'\', \'%\') and Num LIKE CONCAT(\'${obj.Num}%\', \'\', \'%\') and local LIKE CONCAT(\'${obj.local}%\', \'\', \'%\') and StartDate LIKE CONCAT(\'${obj.StartDate}%\', \'\', \'%\') and ScrapDate LIKE CONCAT(\'${obj.ScrapDate}%\', \'\', \'%\') and ManagerName LIKE CONCAT(\'${obj.ManagerName}%\', \'\', \'%\') and ManagerPhone LIKE CONCAT(\'${obj.ManagerPhone}%\', \'\', \'%\')`
                }
            };
            axios.request(options).then(response => {
                // console.log(response.data.data);
                this.tableData = response.data.data
            }).catch(function (error) {
                console.error(error);
            });
        },
        operate(val) {
            if (val === '新增') {
                this.$refs.dialog.dialogVisible = true;
                this.title = '新增'
                this.dialogList = {
                    所属厂区: "",
                    物资类型: "",
                    物资编号: "",
                    物资名称: "",
                    物资规格: "",
                    物资单位: "",
                    物资数量: "",
                    所在位置: "",
                    物资开始日期: "",
                    物资报废日期: "",
                    负责人姓名: "",
                    负责人电话: "",
                };
            } else if (val === '删除') {
                const list = this.multipleSelection.map(item => {
                    return `('${item.所属厂区}', '${item.物资类型}', '${item.物资编号}')`;
                }).join(',');
                if (this.multipleSelection.length === 0) {
                    this.$message({
                        message: '请选择要删除的数据',
                        type: 'warning'
                    });
                    return
                } else {
                    this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                        center: true,
                    }).then(() => {
                        const options = {
                            method: 'POST',
                            url: 'http://10.199.98.2:8086/3DInterface_D/Business/EmergManage/Platform/yjwz_bb_zsgc',
                            data: {
                                TIP: 'delete',
                                SQL: `DELETE FROM imp_emergmanage.emerg_matlist WHERE (FactoryArea, Type, No) IN (${list})`
                            }
                        };

                        axios.request(options).then(response => {
                            if (response.data.message === "success") this.$message.success("删除成功");
                            this.getTable(this.List)
                        }).catch(function (error) {
                            console.error(error);
                        });
                    }).catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除",
                        });
                    });
                }
            }
        },
        handleClick(row) {
            this.$refs.dialog.dialogVisible = true;
            this.title = '编辑'
            this.dialogList = JSON.parse(JSON.stringify(row));
            this.oldData = JSON.parse(JSON.stringify(row));
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        addEventListener(obj, title) {
            obj.物资报废日期 = dayjs(obj.物资报废日期).format('YYYY-MM-DD')
            obj.物资开始日期 = dayjs(obj.物资开始日期).format('YYYY-MM-DD')
            if (title === '编辑') {
                const options = {
                    method: 'POST',
                    url: 'http://10.199.98.2:8086/3DInterface_D/Business/EmergManage/Platform/yjwz_bb_zsgc',
                    data: {
                        TIP: 'UPDATE',
                        SQL: `UPDATE imp_emergmanage.emerg_matlist 
                        SET
                        FactoryArea = '${obj.所属厂区}', type = '${obj.物资类型}', no = '${obj.物资编号}', Name = '${obj.物资名称}', Specs = '${obj.物资规格}', Unit = '${obj.物资单位}',Num = '${obj.物资数量}', Local = '${obj.所在位置}', StartDate = '${obj.物资开始日期}', ScrapDate = '${obj.物资报废日期}', ManagerName = '${obj.负责人姓名}', ManagerPhone = '${obj.负责人电话}'
                        WHERE
                        FactoryArea = '${this.oldData.所属厂区}' and type = '${this.oldData.物资类型}' and no = '${this.oldData.物资编号}'`
                    }
                };
                axios.request(options).then(response => {
                    console.log(response.data);
                    if (response.data.message === "success") this.$message.success("编辑成功");
                    this.getTable(this.List)
                }).catch(function (error) {
                    console.error(error);
                });

            } else if (title === '新增') {
                const options = {
                    method: 'POST',
                    url: 'http://10.199.98.2:8086/3DInterface_D/Business/EmergManage/Platform/yjwz_bb_zsgc',
                    data: {
                        TIP: 'INSERT',
                        SQL: `INSERT INTO imp_emergmanage.emerg_matlist  ( FactoryArea, Type, No, Name, Specs, Unit, Num, Local, StartDate, ScrapDate, ManagerName, ManagerPhone) VALUES ('${obj.所属厂区}', '${obj.物资类型}','${obj.物资编号}', '${obj.物资名称}','${obj.物资规格}', '${obj.物资单位}','${obj.物资数量}', '${obj.所在位置}','${obj.物资开始日期}', '${obj.物资报废日期}','${obj.负责人姓名}', '${obj.负责人电话}')`
                    }
                };
                axios.request(options).then(response => {
                    if (response.data.message === "success") this.$message.success("添加成功");
                    else this.$message.error("添加失败");
                    this.getTable(this.List)
                }).catch(function (error) {
                    console.error(error);
                });
            }

        }
    },
    mounted() {
        this.getList()
        this.getTable(this.List)
    },
}
</script>
<style lang="scss" scoped>
.MaterialManage {
    width: 100%;
    height: 995px;
    padding: 24px 0;
    font-family: "Source Han Sans CN";
    font-style: normal;

    .flex {
        display: flex;
        justify-content: space-between;
    }

    .condition {
        width: (1672 / 1720) * 100%;
        margin: 0 auto 16px;

        .condition_1 {
            margin-bottom: 24px;
            width: 100%;
            height: 32px;

            .name {
                width: (450 / 1672) * 100%;
                height: 32px;
                line-height: 32px;
                display: flex;
                justify-content: flex-start;
                color: #163154;
                font-size: 16px;
                font-weight: 700;

                div {
                    margin-right: 10px;
                }

                .filter {
                    color: #165DFF;
                    text-align: right;
                    font-size: 14px;
                    font-weight: 400;
                    margin-left: 10px;

                    &:hover {
                        cursor: pointer;
                    }
                }
            }

            .btn {
                width: 155px;

                div {
                    width: 73px;
                    height: 32px;
                    line-height: 32px;
                    text-align: center;
                    font-size: 14px;
                    font-weight: 350;
                    border-radius: 4px;

                    &:hover {
                        cursor: pointer;
                    }

                    &:nth-child(1) {
                        border: 1px solid #165DFF;
                        color: rgba(22, 93, 255, 0.70);
                    }

                    &:nth-child(2) {
                        background: #165DFF;
                        color: #FFF;
                        font-weight: 700;
                    }
                }
            }
        }

        .condition_2 {
            margin: 0 auto 8px;
            width: (1608 / 1672) * 100%;
            height: 107px;
            border-radius: 1.792px;
            background: rgba(22, 93, 255, 0.05);
            padding: 16px 24px;
            display: flex;
            justify-content: flex-start;
            flex-wrap: wrap;

            &>div {
                margin-right: (50 / 1608) * 100%;
                margin-bottom: 10px;

                &:nth-child(5n) {
                    margin-right: 0;
                }
            }

            .List {
                width: (272 / 1608) * 100%;
                height: 32px;
                line-height: 32px;
                color: #6A788D;
                font-size: 14px;
                font-weight: 400;

                &>div:nth-child(1) {
                    width: 71px;
                    text-align: right;
                }
            }
        }

        .condition_3 {
            margin: 0 auto;
            width: (1608 / 1672) * 100%;
            display: flex;
            justify-content: flex-start;

            div {
                height: 22px;
                line-height: 22px;
                padding: 0 8px;
                margin-right: 6px;
                border-radius: 3.583px;
                background: #F2F3F5;
                color: #4E5969;
                font-size: 12px;
                font-weight: 400;

                .el-icon-close {
                    margin-left: 2px;

                    &:hover {
                        cursor: pointer;
                    }
                }
            }
        }

        ::v-deep .el-input {
            width: 185px !important;
        }

        ::v-deep .el-input--medium .el-input__inner {
            height: 32px !important;
            line-height: 32px !important;
        }
    }

    .Line {
        width: (1672 / 1720) * 100%;
        height: 1px;
        background-color: #165DFF;
        margin: 0 auto;
    }

    .Btn {
        width: (1672 / 1720) * 100%;
        margin: 24px auto 12px;

        .BtnList {
            width: 142px;
            height: 24px;

            &>div {
                width: 68px;
                height: 24px;
                line-height: 24px;
                text-align: center;
                border-radius: 4px;

                &:hover {
                    cursor: pointer;
                }

                i {
                    margin-right: 5px;
                }

                &:nth-child(1) {
                    background: #165DFF;
                    color: #FFF;
                    font-size: 14px;
                    font-weight: 700;
                }

                &:nth-child(2) {
                    border: 1px solid #165DFF;
                    color: rgba(22, 93, 255, 0.70);
                    font-size: 14px;
                    font-weight: 350;
                }
            }
        }
    }


    .table {
        margin: 0 auto;
        width: (1672 / 1720) * 100%;

        ::v-deep .el-table .el-table__header-wrapper th,
        .el-table .el-table__fixed-header-wrapper th {
            background-color: rgba(22, 93, 255, 0.05);
            color: #6A788D;
            font-size: 14px;
            font-weight: 500;
        }

        ::v-deep .el-table--enable-row-hover .el-table__body tr:hover>td {
            background: rgba(22, 93, 255, 0.10) !important;
        }
    }
}
</style>